<template>
  <div class="dashboard">
    <div class="page-header">
      <div class="title">首页</div>
      <div class="subtitle">系统概览与快捷信息</div>
    </div>

    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon user-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.userCount }}</div>
              <div class="stat-label">用户总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon role-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.roleCount }}</div>
              <div class="stat-label">角色总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon permission-icon">
              <el-icon><Key /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.permissionCount }}</div>
              <div class="stat-label">权限总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon online-icon">
              <el-icon><Monitor /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.onlineCount }}</div>
              <div class="stat-label">在线用户</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 快捷入口 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>快捷入口</span>
          </template>
          <div class="quick-actions">
            <div class="quick-grid">
              <div class="quick-item" @click="go('/user')" v-if="hasUserPermission">
                <div class="quick-icon user-bg">
                  <el-icon><User /></el-icon>
                </div>
                <div class="quick-content">
                  <div class="quick-title">用户管理</div>
                  <div class="quick-desc">管理系统用户信息</div>
                </div>
              </div>
              
              <div class="quick-item" @click="go('/role')" v-if="hasRolePermission">
                <div class="quick-icon role-bg">
                  <el-icon><UserFilled /></el-icon>
                </div>
                <div class="quick-content">
                  <div class="quick-title">角色管理</div>
                  <div class="quick-desc">配置用户角色权限</div>
                </div>
              </div>
              
              <div class="quick-item" @click="go('/permission')" v-if="hasPermissionPermission">
                <div class="quick-icon permission-bg">
                  <el-icon><Key /></el-icon>
                </div>
                <div class="quick-content">
                  <div class="quick-title">权限管理</div>
                  <div class="quick-desc">管理系统权限配置</div>
                </div>
              </div>
              
              <div class="quick-item" @click="go('/profile')">
                <div class="quick-icon profile-bg">
                  <el-icon><User /></el-icon>
                </div>
                <div class="quick-content">
                  <div class="quick-title">个人信息</div>
                  <div class="quick-desc">查看和编辑个人信息</div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 权限类型分布（环形仪表盘） -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>权限类型分布</span>
          </template>
          <div class="permission-distribution">
            <div class="progress-item">
              <el-progress type="dashboard" :percentage="menuPercent" :color="'#409EFF'" :width="120" />
              <div class="progress-label">菜单（{{ permissionStats.menu }}）</div>
            </div>
            <div class="progress-item">
              <el-progress type="dashboard" :percentage="buttonPercent" :color="'#67C23A'" :width="120" />
              <div class="progress-label">按钮（{{ permissionStats.button }}）</div>
            </div>
            <div class="progress-item">
              <el-progress type="dashboard" :percentage="otherPercent" :color="'#E6A23C'" :width="120" />
              <div class="progress-label">其它（{{ permissionStats.other }}）</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>系统信息</span>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="系统名称">RBAC权限控制系统</el-descriptions-item>
            <el-descriptions-item label="系统版本">v1.0.0</el-descriptions-item>
            <el-descriptions-item label="Java版本">Java 8</el-descriptions-item>
            <el-descriptions-item label="数据库">MySQL 5.7</el-descriptions-item>
            <el-descriptions-item label="前端框架">Vue 3 + Element Plus</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>最近登录</span>
          </template>
          <div class="recent-login">
            <div class="login-item">
              <el-avatar :size="40" :src="user.avatar">
                {{ user.realName?.charAt(0) || user.username?.charAt(0) }}
              </el-avatar>
              <div class="login-info">
                <div class="login-user">{{ user.realName || user.username }}</div>
                <div class="login-time">刚刚登录 · {{ clientInfo.browser }} · {{ clientInfo.os }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import request from '@/api/request'

const router = useRouter()
const go = (path) => router.push(path)

const authStore = useAuthStore()
const user = authStore.user

// 权限检查
const hasUserPermission = computed(() => {
  return authStore.hasPermission('system:user:query')
})

const hasRolePermission = computed(() => {
  return authStore.hasPermission('system:role:query')
})

const hasPermissionPermission = computed(() => {
  return authStore.hasPermission('system:permission:query')
})

const stats = ref({
  userCount: 0,
  roleCount: 0,
  permissionCount: 0,
  onlineCount: 1
})

const clientInfo = ref({ browser: 'Chrome', os: 'Windows' })

// 权限分布
const permissionStats = ref({ menu: 0, button: 0, other: 0 })
const menuPercent = ref(0)
const buttonPercent = ref(0)
const otherPercent = ref(0)

onMounted(async () => {
  // 获取统计数据
  try {
    const resp = await request({ url: '/dashboard/stats', method: 'get' })
    if (resp.data && resp.data.code === 200) {
      const d = resp.data.data || {}
      stats.value = {
        userCount: d.userCount || 0,
        roleCount: d.roleCount || 0,
        permissionCount: d.permissionCount || 0,
        onlineCount: d.onlineCount || 1
      }
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }

  // 简单 UA 解析
  const ua = navigator.userAgent
  clientInfo.value = {
    browser: /Chrome\//.test(ua) ? 'Chrome' : /Firefox\//.test(ua) ? 'Firefox' : 'Browser',
    os: /Windows/.test(ua) ? 'Windows' : /Mac OS/.test(ua) ? 'macOS' : /Linux/.test(ua) ? 'Linux' : 'OS'
  }

  // 权限分布数据从统计数据中获取，避免额外的API调用
  const totalPermissions = stats.value.permissionCount || 0
  if (totalPermissions > 0) {
    // 这里可以根据实际需求设置默认分布
    permissionStats.value = { 
      menu: Math.floor(totalPermissions * 0.4), 
      button: Math.floor(totalPermissions * 0.5), 
      other: totalPermissions - Math.floor(totalPermissions * 0.4) - Math.floor(totalPermissions * 0.5)
    }
    const total = totalPermissions
    menuPercent.value = Math.round(permissionStats.value.menu * 100 / total)
    buttonPercent.value = Math.round(permissionStats.value.button * 100 / total)
    otherPercent.value = 100 - menuPercent.value - buttonPercent.value
  }
})
</script>

<style scoped>
.dashboard { padding: 20px; }
.page-header { margin-bottom: 16px; }
.title { font-size: 20px; font-weight: 600; color: #303133; }
.subtitle { font-size: 13px; color: #909399; margin-top: 4px; }

.stat-card { height: 120px; }
.stat-content { display: flex; align-items: center; height: 100%; }
.stat-icon { width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-right: 20px; font-size: 24px; color: white; }
.user-icon { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.role-icon { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.permission-icon { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.online-icon { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.stat-info { flex: 1; }
.stat-number { font-size: 28px; font-weight: bold; color: #333; margin-bottom: 5px; }
.stat-label { font-size: 14px; color: #666; }

.quick-actions { padding: 16px; }
.quick-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
.quick-item { 
  display: flex; 
  flex-direction: column; 
  align-items: center; 
  padding: 20px 16px; 
  border-radius: 12px; 
  background: #f8f9fa; 
  cursor: pointer; 
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
  text-align: center;
}
.quick-item:hover { 
  background: #e3f2fd; 
  border-color: #2196f3; 
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.15);
}
.quick-icon { 
  width: 56px; 
  height: 56px; 
  border-radius: 16px; 
  display: flex; 
  align-items: center; 
  justify-content: center; 
  margin-bottom: 12px; 
  font-size: 24px; 
  color: white; 
}
.user-bg { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.role-bg { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.permission-bg { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.profile-bg { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.quick-content { text-align: center; }
.quick-title { font-size: 16px; font-weight: 600; color: #333; margin-bottom: 6px; }
.quick-desc { font-size: 12px; color: #666; line-height: 1.4; }
.permission-distribution { display: flex; gap: 24px; align-items: center; justify-content: space-around; }
.progress-item { display: flex; flex-direction: column; align-items: center; }
.progress-label { margin-top: 8px; font-size: 13px; color: #606266; }

.recent-login { padding: 10px 0; }
.login-item { display: flex; align-items: center; padding: 15px 0; border-bottom: 1px solid #f0f0f0; }
.login-item:last-child { border-bottom: none; }
.login-info { margin-left: 15px; }
.login-user { font-size: 16px; font-weight: 500; color: #333; margin-bottom: 5px; }
.login-time { font-size: 14px; color: #999; }
</style> 